﻿using System;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.Services;
using BluePortal.Medias.Core;

namespace BluePortal.QuikStart.WSAjax
{
    [WebService(Namespace = "BluePortal.QuikStart.WSAjax")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SilverligthFileUploadService : System.Web.Services.WebService
    {
        public SilverligthFileUploadService() { }

        [WebMethod]
        public void SendChunk(string fileName, bool isNew, string base64Encoded)
        {
            Thread.Sleep(100);
            fileName = HttpUtility.UrlDecode(fileName);
            base64Encoded = HttpUtility.UrlDecode(base64Encoded);
            base64Encoded = base64Encoded.Replace(' ', '+');
            //string path = Server.MapPath("/_uploadvideotmp/" + fileName);
            string path = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadedVideoDirectory"] + @"\" + fileName;
            byte[] b = Convert.FromBase64String(base64Encoded);

            FileStream fs = null;
            int attempts = 0;
            while (fs == null && attempts < 3)
            {
                try
                {
                    if (isNew || !File.Exists(path))
                    {
                        fs = File.Create(path);
                    }
                    else
                    {
                        fs = File.Open(path, FileMode.Append);
                    }
                }
                catch (Exception)
                {
                    attempts++;
                    Thread.Sleep(50);
                }
            }
            fs.Write(b, 0, b.Length);
            fs.Close();

            //Mix workaround for Safari browser stack
            Context.Response.Write(" ");
        }

        [WebMethod]
        public void FileUploaded(string videoID)
        {
            Guid vid = new Guid(videoID);
            BCVideo bcvideo = new BCVideo();
            Video video = bcvideo.FindVideoByID(vid);
            if (video == null)
            {
                video = new Video() { ID = vid, Owner = HttpContext.Current.User.Identity.Name, Title = vid.ToString() };
                bcvideo.Create(video);
            }            
        }
    }
}